package org.com.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Component
public class AliOssUtil {
    private final static   String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
    // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
    // EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
    private final static String ACCESSKEY_ID="LTAI5tHAj5deKM9vu8bZD3zg";
    private final static String ACCESSKEY_SECRET="ygJNgFTzbkeBxsCwP3d9NBH1NaqbVE";
    // 填写Bucket名称，例如examplebucket。
    private final static String BUCKET_NAME = "susu-plants";

    //上传文件,返回文件的公网访问地址
    public String upload(MultipartFile multipartFile)throws IOException {
        InputStream inputStream = multipartFile.getInputStream();
//避免文件覆盖
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"))+ multipartFile.getOriginalFilename();
//上传文件到 0SS
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESSKEY_ID, ACCESSKEY_SECRET);
        ossClient.putObject(BUCKET_NAME,fileName,inputStream);
//文件访问路径
        String url = ENDPOINT.split( "//")[0]+"//"+ BUCKET_NAME + "." +ENDPOINT.split( "//")[1]+"/"+ fileName;
        ossClient.shutdown();
        return url;//把上传到
    }
}
